<template>
  <div>
    <div style="display: flex">
      <div class="left-class">
        <div class="top-buton" style="margin-bottom: 16px">
          <span>
            <el-button type="primary" style="margin: 0 5px" icon="el-icon-plus"  @click="exchangeThat">添加组织</el-button>
            <el-button  style="margin: 0 5px" icon="el-icon-delete" type="danger" @click="deleteThat">移除组织</el-button>
            <el-button style="margin: 0 5px" type="primary"  :icon="isExpand ? 'el-icon-caret-top' : 'el-icon-caret-bottom'" @click="unfoldThat">{{ isExpand ? '折叠组织' : '展开组织' }}</el-button>
          </span>
          <span></span>
        </div>
        <div style="margin-bottom: 15px">
          <el-input placeholder="输入组织名称关键字查询" v-model="filterText">
          </el-input>
        </div>
        <el-tree v-if="treeData.length > 0" class="filter-tree" highlight-current :expand-on-click-node="false" @current-change="changeTreeData" :render-content="renderContent" :data="treeData" :props="defaultProps" :filter-node-method="filterNode" default-expand-all ref="myTree">
        </el-tree>
        <div v-if="treeData.length == 0" class="zwsj">
          <div>
            <span>暂无数据</span>
          </div>
        </div>
      </div>
      <div class="right-class">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基本信息" name="1">
            <el-form ref="formUser" :model="userData" :rules="rulesUser" label-width="80px">
              <el-form-item label="组织名称" prop="name">
                <el-input v-model="userData.name" placeholder="请输入组织名称" />
              </el-form-item>
              <el-form-item label="组织类型" prop="type">
                <el-select style="width: 100%"  v-model="userData.type" placeholder="请选择机构类型">
                  <el-option v-for="(item, index) in optionList" :key="index" :value="item.value" :label="item.label"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="排序" prop="sort">
                <el-input v-model="userData.sort" type="number" placeholder="请输入排序号" />
              </el-form-item>
              <el-form-item v-if="userData.type == 2" label="经度" prop="long">
                <el-input v-model="userData.long" type="number" placeholder="请输入经度" />
              </el-form-item>
              <el-form-item v-if="userData.type == 2" label="纬度" prop="lat">
                <el-input v-model="userData.lat" type="number" placeholder="请输入纬度" />
              </el-form-item>
              <el-form-item v-if="userData.type == 2" label="电厂地址" prop="address">
                <el-input v-model="userData.address" placeholder="请输入电厂地址" />
              </el-form-item>
              <el-form-item label="备注" prop="remarks">
                <el-input v-model="userData.remarks" type="textarea" :autosize="{ minRows: 5, maxRows: 10}" placeholder="请输入备注"></el-input>
              </el-form-item>
              <el-form-item>
                <div class="button_item">
                  <el-button type="primary" :loading="loading"  @click="addFrom">保存</el-button>
                </div>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="组织成员" name="2">
            <div class="top-search" style="
                margin: 0;
                border: 0;
                padding-left: 0;
                padding-right: 0;
                margin-left: 0;
                margin-right: 0;
              ">
              <el-form :model="queryParams" label-width="70px" >
                <el-row :gutter="30">
                  <el-col :span="6">
                    <el-form-item label="工号" prop="code">
                      <el-input v-model="queryParams.code" placeholder="请输入工号"   @keyup.enter.native="searchList" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="姓名" prop="name">
                      <el-input v-model="queryParams.name" placeholder="请输入名称"   @keyup.enter.native="searchList" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="联系电话" prop="phoneNo">
                      <el-input v-model="queryParams.phoneNo" placeholder="请输入联系电话"   @keyup.enter.native="searchList" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item class="searchFromButton">
                      <el-button  type="primary" icon="el-icon-search" @click="searchList">查询</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div style="
                margin: 0;
                border: 0;
                padding-left: 0;
                padding-right: 0;
                margin-left: 0;
              ">
              <hu-table :tableData="tableData" :loading="loading" :tableCol="tableCol">
                <template v-slot:gender="{ row }">
                  <p v-if="row.gender != null">{{ row.gender ? '男' : '女' }}</p>
                </template>
                <template v-slot:head="{ row }">
                  <el-image style="height: 60px; width: 60px; border-radius: 50%;" fit="fill" :src="$config.imgUrl + row.headPortraitPath" :preview-src-list="[$config.imgUrl + row.headPortraitPath]">
                    <div slot="error" class="image-slot">
                      <img src="@/assets/images/morenImg.png" style="height: 60px; object-fit: cover" />
                    </div>
                  </el-image>
                </template>
              </hu-table>
              <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <hu-modal :title="'添加组织'" :show-modal.sync="addModal" :loading="loading" @close="cancel" @submit="changeOrAdd">
      <el-form ref="queryForm" :model="addData" :rules="rules" label-width="100px">
        <el-form-item label="上级菜单" prop="parentId">
          <treeselect v-model="addData.parentId" :options="treeData" :normalizer="normalizer" :show-count="true" placeholder="选择上级菜单" />
        </el-form-item>
        <el-form-item label="组织类型" prop="type">
          <el-select   style="width: 100%" v-model="addData.type" placeholder="请选择机构类型">
            <el-option v-for="(item, index) in optionList" :key="index" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="addData.type == 2" label="经度" prop="long">
          <el-input v-model="addData.long" type="number" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item v-if="addData.type == 2" label="纬度" prop="lat">
          <el-input v-model="addData.lat" type="number" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="addData.name" type="text" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="addData.code" type="text"></el-input>
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number v-model="addData.sort" :step="1" style="width: 100%; float: left"></el-input-number>
        </el-form-item>
      </el-form>
    </hu-modal>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  getTree, // 查询列表
  addList,
  getList,
  updateList,
  deleteList,
} from "@/api/system/tissue";
export default {
  dicts: [],
  name: "SystemOrganizationall",
  components: {
    Treeselect,
  },
  computed: {},
  watch: {
    filterText(val) {
      this.$refs.myTree.filter(val);
    },
  },
  data() {
    return {
      optionList: [
        { value: 0, label: "公司" },
        { value: 1, label: "监察中心" },
        { value: 2, label: "电厂" },
        { value: 3, label: "部门" },
        { value: 5, label: "班组" },
      ],
      activeName: "1",
      // tree是否全选，复选框默认状态（）
      isExpand: true,
      filterText: "",
      userData: {},
      rules: {
        parentId: [
          { required: true, message: "上级菜单不能为空", trigger: "change" },
        ],
        type: [
          { required: true, message: "机构类型不能为空", trigger: "change" },
        ],
        name: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        code: [{ required: true, message: "编码不能为空", trigger: "blur" }],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
      },
      rulesUser: {
        name: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        type: [
          { required: true, message: "机构类型不能为空", trigger: "change" },
        ],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
        // remarks: [
        //   { required: true, message: "备注不能为空", trigger: "blur" }
        // ],
      },
      addModal: false,
      loading: false,
      treeData: [],
      chooseTreeData: {},
      defaultProps: {
        children: "child",
        label: "name",
      },
      addData: {
        parentId: undefined,
        name: undefined,
        code: undefined,
        remarks: undefined,
        phone: undefined,
        type: undefined,
        sort: 0,
      },
      rowList: {},
      // two-------------------
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0, // table total
      // table Col
      tableCol: [
        {
          title: "序号",
          type: "index",
          width: "55",
        },
        {
          title: "头像",
          slot: "head",
          width: "80",
        },
        {
          title: "工号",
          key: "code",
          minWidth: "100",
        },
        {
          title: "姓名",
          key: "name",
          minWidth: "100",
        },
        {
          title: "性别",
          slot: "gender",
          minWidth: "80",
        },
        {
          title: "年龄",
          key: "age",
          minWidth: "80",
        },
        {
          title: "学历",
          key: "educationName",
          minWidth: "100",
        },
        {
          title: "身份证号",
          key: "identityCardNo",
          minWidth: "170",
        },
        {
          title: "联系电话",
          key: "phoneNo",
          minWidth: "150",
        },
        {
          title: "邮箱",
          key: "email",
          minWidth: "170",
        },
      ],
      tableData: [],
    };
  },
  mounted() {
    this.getTree();
  },
  methods: {
    // 列表 List
    getList() {
      this.loading = true;
      let params = {
        ...this.queryParams,
        orgId: this.rowList.id,
      };
      getList(params).then(({ stateCode, result }) => {
        if (stateCode == 200) {
          this.loading = false;
          this.tableData = result.records;
          this.total = result.total;
        }
      });
    },
    // 查询 list
    searchList() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 基本信息 提交
    addFrom() {
      if (!this.rowList.id) return this.$modal.msg("请选择组织节点");
      this.$refs["formUser"].validate((valid) => {
        if (valid) {
          let params = {
            ...this.userData,
            location: this.userData.long + "&" + this.userData.lat,
          };
          this.loading = true;
          updateList(params).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.getTree();
            this.loading = false;
          });
        }
      });
    },
    // tree update
    renderContent(h, { node, data, store }) {
      let element = null;
      if (node.level === 1) {
        return (
          <span class="custom-tree-node">
            <span>
              <i class="el-icon-s-home tree-icon-style"></i>
              {node.label}
            </span>
            <span>
              <el-button
                
                class="treeButText"
                type="text"
                on-click={() => this.append(data)}
              >
                新增
              </el-button>
              <el-button
                class="test"
                
                class="treeBut"
                type="text"
                on-click={() => this.remove(node, data)}
              >
                删除
              </el-button>
            </span>
          </span>
        );
      } else {
        return (
          <span class="custom-tree-node">
            <span>{node.label}</span>
            <span>
              <el-button
                
                class="treeButText"
                type="text"
                on-click={() => this.append(data)}
              >
                新增
              </el-button>
              <el-button
                
                class="treeBut"
                type="text"
                on-click={() => this.remove(node, data)}
              >
                删除
              </el-button>
            </span>
          </span>
        );
      }
    },
    append(data) {
      this.reset();
      this.addData = {
        parentId: data.id,
      };
      this.addModal = true;
    },

    remove(node, data) {
      this.$modal.confirm("确定删除“" + data.name + "”数据项？").then(() => {
        this.remove1(node, data);
      });
    },
    remove1(node, data) {
      this.$modal
        .confirm(
          "确定删除“" +
            data.name +
            "”数据项？删除后将无法恢复，且影响该组织下项目数据，请谨慎操作！"
        )
        .then(() => {
          return deleteList(data.id);
        })
        .then((res) => {
          if (res.stateCode == 200) {
            this.$store.dispatch("GetMation").then(() => {
              this.$modal.msgSuccess("删除成功");
              this.getTree();
            });
          }
        });
    },
    handleClick(tab, event) {},
    unfoldThat() {
      // 改变一个全局变量
      this.isExpand = !this.isExpand;
      // 改变每个节点的状态
      this.changeTreeNodeStatus(this.$refs.myTree.store.root);
    },
    // 改变节点的状态
    changeTreeNodeStatus(node) {
      node.expanded = this.isExpand;
      for (let i = 0; i < node.childNodes.length; i++) {
        // 改变节点的自身expanded状态
        node.childNodes[i].expanded = this.isExpand;
        // 看看他孩子的长度，有的话就调用自己往下找
        if (node.childNodes[i].childNodes.length > 0) {
          this.changeTreeNodeStatus(node.childNodes[i]);
        }
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 取消按钮
    cancel() {
      this.addModal = false;
      this.reset();
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.child,
      };
    },
    getTree() {
      this.loading = true;
      getTree(this.$store.getters.userInfo.orgId).then(
        ({ result, stateCode }) => {
          if (stateCode == 200) {
            this.loading = false;
            this.treeData = [result];
          } else {
            this.$Message["warning"]({
              background: true,
              content: res.message,
            });
          }
        }
      );
    },
    // 表单重置
    reset() {
      this.addData = {
        parentId: undefined,
        name: undefined,
        code: undefined,
        remarks: undefined,
        phone: undefined,
        type: undefined,
        sort: 0,
      };
      this.resetForm("queryForm");
    },
    exchangeThat() {
      this.reset();
      this.addModal = true;
    },
    changeOrAdd() {
      this.$refs["queryForm"].validate((valid) => {
        if (valid) {
          let params = {
            ...this.addData,
            location: this.addData.long + "&" + this.addData.lat,
          };
          addList(params).then(({ result }) => {
            if (result) {
              this.$store.dispatch("GetMation").then(() => {
                this.$modal.notifySuccess("新增成功");
                this.getTree();
                this.addModal = false;
              });
            }
          });
        }
      });
    },
    deleteThat() {
      if (!this.rowList.id) return this.$modal.msg("请先选择数据项");
      this.$modal
        .confirm("确定删除“" + this.rowList.name + "”数据项？")
        .then(() => {
          return deleteList(this.rowList.id);
        })
        .then((res) => {
          if (res.stateCode == 200) {
            this.$store.dispatch("GetMation").then(() => {
              this.$modal.msgSuccess("删除成功");
              this.getTree();
            });
          }
        });
    },
    changeTreeData(data, index) {
      this.rowList = data;
      this.userData = {
        name: data.name,
        type: data.type,
        sort: data.sort,
        remarks: data.remarks,
        id: data.id,
        powerPlantType: data.powerPlantType,
        address: data.address,
        long: data.location ? data.location.split("&")[0] : "",
        lat: data.location ? data.location.split("&")[1] : "",
      };
      this.searchList();
    },
  },
};
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  margin-left: 0;
  padding-right: 8px;
}
.tree-icon-style {
  color: #496dff;
  padding-right: 4px;
}
.treeBut {
  color: #fe5a57;
}
.treeBut:hover {
  color: #ff6b68;
}
</style>

<style lang="scss" scoped>
::v-deep .el-tree-node__content {
  height: 35px !important;
}
::-webkit-scrollbar {
  width: 0 !important;
}
::-webkit-scrollbar {
  width: 0 !important;
  height: 0;
}

.left-class {
  overflow: auto;
  flex: 0 0 370px;
  margin-left: 15px;
  padding: 20px 8px;
  height: calc(100vh - 154px);
  background: #fff;
  border-radius: 3px;
}
.tree {
  border: 1px solid #eaeaea;
  height: calc(100vh - 245px);
  overflow-y: auto;
  padding: 10px;
  .zwsj {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    div {
      width: 150px;
      height: 150px;
      background-size: 100%;
      position: relative;
      span {
        display: block;
        width: 100%;
        text-align: center;
        position: absolute;
        color: #999;
        bottom: 0;
      }
    }
  }
}
.right-class {
  overflow: auto;
  width: calc(100% - 430px);
  flex: 1;
  margin-left: 15px;
  margin-right: 15px;
  background: #fff;
  border-radius: 3px;
  padding: 20px 30px;
  height: calc(100vh - 154px);
}
.button_item {
  text-align: right;
}
</style>
